/**
 * Created by asus on 2016/11/23.
 */
import React, { Component,PropTypes} from 'react';
import {Link} from 'react-router';
import TabBar from '../../Component/CommonComponent/TabBar'
import AllOrderList from '../../Component/CommonComponent/AllOrderList'
import Split from '../CommonComponent/Split'
import Top from '../CommonComponent/Top'
import Empty from '../CommonComponent/Empty'
import Time from '../CommonComponent/Time'
import StockDesc from '../../Component/StockManage/StockDesc';
import CheckBox from '../../Component/OrderManage/CheckBox';
import IsShowEmptyImg from '../CommonComponent/IsShowEmptyImg'
import {bodyScroll} from '../../Action/rpc';
import {EditShopNum,DelShopCar,SettlementShopCar,StockList,AddWarehouseOrder,ListByOrderNo,MyInfo,AddressList} from '../../Action/auth'
import ChangeNum from '../../Component/OrderManage/ChangeNum';
import DelayModal from '../../Component/CommonComponent/DelayModal'
import $ from 'jquery'
import iScroll from "iscroll/build/iscroll-probe";

export default class ReturnGoods extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            WsTog:false,
            StockTog:false,
            index:0,
            listPage:1,
            goodsList:[],
            stockList:[],
            tipMsg:true
        };
        this.isUseSelectAll = false;
        this.amount = 0;
        this.select = [];
        this.selectNum = [];
        this.selectDel = [];
        this.selectStock = [];
        this.click = true;
        this.page = 1;
        this.list=[];
        this.loadingStep = 0;
    }

    static contextTypes = {
        router:PropTypes.object
    }

    async componentWillMount() {
        let indexValue = this.props.location.query.index;
        this.setState({index:indexValue?indexValue:0});
        await this.getMyInfo();
        await this.getStockList(1);
        //await this.getLeaderWarehouseList(0,1);
        this.myScroll.refresh();
       /* await this.getAddressList();
        this.getAddress();*/
    }

    componentDidMount() {
        document.querySelector('body').addEventListener('touchmove',bodyScroll, false);

        var pullDownEl = $('#pullDown');
        pullDownEl['class'] = pullDownEl.attr('class');
        pullDownEl.attr('class','').hide();

        var pullUpEl = $('#pullUp');
        pullUpEl['class'] = pullUpEl.attr('class');
        pullUpEl.attr('class','').hide();

        this.myScroll = new iScroll('#content', {
            preventDefault: false,
            probeType: 2,//probeType：1对性能没有影响。在滚动事件被触发时，滚动轴是不是忙着做它的东西。probeType：2总执行滚动，除了势头，反弹过程中的事件。这类似于原生的onscroll事件。probeType：3发出的滚动事件与到的像素精度。注意，滚动被迫requestAnimationFrame（即：useTransition：假）。
            scrollbars: true,//有滚动条
            mouseWheel: true,//允许滑轮滚动
            fadeScrollbars: true,//滚动时显示滚动条，默认影藏，并且是淡出淡入效果
            bounce:true,//边界反弹
            interactiveScrollbars:true,//滚动条可以拖动
            shrinkScrollbars:'scale',// 当滚动边界之外的滚动条是由少量的收缩。'clip' or 'scale'.
            click: true ,// 允许点击事件
            keyBindings:true,//允许使用按键控制
            momentum:true// 允许有惯性滑动
        });
        //滚动时
        this.myScroll.on('scroll', this.scroll );
        this.myScroll.on('touchmove', function(e){e.stopPropagation()});
        //滚动完毕
        this.myScroll.on('scrollEnd',this.scrollEnd );
    }

    scroll=()=>{
        var pullDownEl = $('#pullDown');
        var pullDownL = pullDownEl.find('.pullDownLabel');
        var pullUpEl = $('#pullUp');
        var pullUpL = pullUpEl.find('.pullUpLabel');

        if(this.loadingStep == 0 && !pullDownEl.attr('class').match('flip|loading') && !pullUpEl.attr('class').match('flip|loading')){
            if (this.myScroll.y > 5) {
                //下拉刷新效果
                pullDownEl.attr('class',pullUpEl['class'])
                pullDownEl.show();
                this.myScroll.refresh();
                pullDownEl.addClass('flip');
                pullDownL.html('下拉刷新...');
                this.loadingStep = 1;
            }else if (this.myScroll.y < (this.myScroll.maxScrollY - 5) && this.state.leaderWareList.length>0) {
                if(this.state.listPage!=this.page){
                    //上拉刷新效果
                    pullUpEl.attr('class',pullUpEl['class'])
                    pullUpEl.show();
                    this.myScroll.refresh();
                    pullUpEl.addClass('flip');
                    pullUpL.html('上拉加载...');
                    this.loadingStep = 1;
                }
            }
        }

    }
    scrollEnd=()=>{
        var pullDownEl = $('#pullDown');
        var pullDownL = pullDownEl.find('.pullDownLabel');
        var pullUpEl = $('#pullUp');
        var pullUpL = pullUpEl.find('.pullUpLabel');

        if(this.loadingStep == 1){
            if (pullUpEl.attr('class').match('flip|loading')) {
                pullUpEl.removeClass('flip').addClass('loading');
                pullUpL.html('Loading...');
                this.loadingStep = 2;
                this.pullUpAction();
            }else if(pullDownEl.attr('class').match('flip|loading')){
                pullDownEl.removeClass('flip').addClass('loading');
                pullDownL.html('Loading...');
                this.loadingStep = 2;
                this.pullDownAction();
            }
        }
    }

    pullDownAction() {//下拉事件
        var pullDownEl = $('#pullDown');
        var pullDownL = pullDownEl.find('.pullDownLabel');

        this.page=1;
        this.getStockList(this.page)

        pullDownEl.removeClass('loading');
        pullDownL.html('下拉刷新...');
        pullDownEl['class'] = pullDownEl.attr('class');
        pullDownEl.attr('class','').hide();
        this.myScroll.refresh();
        this.loadingStep = 0;
    }
    pullUpAction() {//上拉事件
        var pullUpEl = $('#pullUp');
        var pullUpL = pullUpEl.find('.pullUpLabel');

        if(this.state.listPage>this.page){
            this.page++;
            this.getStockList(this.page)
            //this.getLeaderWarehouseList(this.state.index,this.page)
        }
        pullUpEl.removeClass('loading');
        pullUpL.html('上拉显示更多...');
        pullUpEl['class'] = pullUpEl.attr('class');
        pullUpEl.attr('class','').hide();
        this.myScroll.refresh();
        this.loadingStep = 0;
    }

    componentWillUnmount() {
        document.querySelector('body').removeEventListener('touchmove',bodyScroll, false);
    }

    async onChange(index){
        if(index != this.state.index){
            this.setState({stockList:[]});
            this.list=[];
            this.page=1;
            this.selectStock=[];
            await this.setState({index:index})
            if(this.state.index == '0'){
                await this.getStockList(this.page)
                this.myScroll.refresh();
            }else if(this.state.index == 1){
                await this.getStockList(this.page)
                this.myScroll.refresh();
            }
        }
    }

    async getMyInfo(){
        await MyInfo()
            .then(res=>{
                this.setState({grade:res.AGENT_GRADE})
            })
    }

    async getStockList(page){
        await StockList(page)
            .then(res=>{
                const page = Math.ceil(res.total/res.pageSize);
                this.setState({listPage:page})
                if(page==1){
                    this.list = res.resultList;
                    this.setState({stockList:this.list})
                }else{
                    this.list = this.list.concat(res.resultList);
                    this.setState({stockList:this.list})
                }
                this.myScroll.refresh();
            })
            .catch(err=>{
                alert(err.message)
                console.warn('err',err)
            })
    }

    submit(stock,whStock,Id,name,image,index,price){
        let num = parseInt(this.refs['num'+index].value);
        if(isNaN(num)){
            this.refs['num'+index].value=num=0
        }
        if(num<0||num==''){
            this.refs['num'+index].value=num=0
        }else{
            this.refs['num'+index].value=num
        }
        if(this.state.index==0){
            if(num>stock){
                this.refs['num'+index].value=stock
            }
        }else{
            if(num>whStock){
                this.refs['num'+index].value=whStock
            }
        }

        if(this.selectStock.length==0 && num>0){
            this.selectStock.push({productId:Id,num:num,price:price});
        }else{
            for(var i=0;i<this.selectStock.length;i++){
                if(this.selectStock[i].productId==Id){
                    this.selectStock.splice(i,1)
                }
            }
            if(num>0){
                this.selectStock.push({productId:Id,num:num,price:price});
            }
        }
    }



    toChangePage(){
        if(this.selectStock.length==0){
            alert('退货总数量不能为0')
        }else{
            console.log('价格',this.selectStock)
            this.context.router.push({pathname:'/exchangeGoods',query:{index:this.state.index,returnJson:JSON.stringify(this.selectStock)}})
        }
    }

    render(){
        const {stockList,index}=this.state;
        return(
            <div className="f14">
                <Top
                    title ={'退货'}
                />
                {/*<div className="pf width100" style={{top:50}}>
                    <AllOrderList
                        index = {index}
                        onClick = {index=>this.onChange(index)}
                        /!*contents={['全部','待发货','已发货','已完成','申请取消','已取消','已审单']}*!/
                        contents={['虚仓','实仓']}
                    />
                </div>*/}
                <div id="content" className="bkg_color" style={{top:50,bottom:50}}>
                    <div id="scroller" style={{minHeight:window.innerHeight-139}}>
                        <div id="pullDown" className="ub ub-pc c-gra">
                            <div className="pullDownIcon"></div>
                            <div className="pullDownLabel">下拉刷新</div>
                        </div>
                        <ul id="add">
                            {
                                stockList.length==0?
                                    <Empty />
                                    :
                                stockList&&stockList.map((el,index)=>{
                                    return(
                                    <div>
                                        <div className="padd10 flex flex-pack-justify flex-pack-justify" style={{borderBottom:'1px solid #e5e5e5',marginTop:10}}>
                                            <div><img src={el.IMAGE} style={{width:60,height:60,marginLeft:10}} alt=""/></div>
                                            <div className="flex-v" style={{marginLeft:20}}>
                                                <div>{el.NAME}</div>
                                                {
                                                    this.state.index==0?
                                                        <div>虚仓库存：<span className="di height100 borderno tc" style={{width:60}}>{el.STOCK}</span></div>
                                                        :
                                                        <div>实仓库存：<span className="di height100 borderno tc" style={{width:60}}>{el.WAREHOUSE_STOCK}</span></div>
                                                }
                                                <div>退货数量：
                                                    <input type="number" defaultValue="0" className="di height100 borderno tc"
                                                           style={{width:60,borderBottom:'1px solid #e5e5e5'}}
                                                           ref = {"num" + index}
                                                           onBlur = {()=>this.submit(el.STOCK,el.WAREHOUSE_STOCK,el.ID,el.NAME,el.IMAGE,index,el.price)}
                                                    />
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    )}
                                )
                            }
                        </ul>
                        <div id="pullUp" className="ub ub-pc c-gra">
                            <div className="pullUpIcon"></div>
                            <div className="pullUpLabel">上拉显示更多...</div>
                        </div>
                    </div>
                </div>

                <div className="pf bottomCount flex flex-align-center flex-pack-center plr width100 colorfff f18"
                     style={{bottom:0,background:'rgba(250, 107, 91,.8)'}}
                     onClick={()=>this.toChangePage()}
                >
                    确定
                </div>
                {
                    this.state.modalDelay?
                        <DelayModal />
                        :null

                }
                {
                    this.state.tipMsg?
                        <div className="modalBar pf width100 height100 f14">
                            <div className="modal_body border_4 scale">
                                <div className="padd10">
                                    1.调换货的商品必须为三个月内的产生的订单;
                                </div>
                                <div className="padd10">
                                    2. 调换货比例为当批次订单总量的20%;
                                </div><div className="padd10 border_bottom">
                                    3.每季度可调整一次；
                                </div>
                                <div style={{height:40,lineHeight:'40px'}}>
                                    <button className="width100 colorlv bkr_Tr borderno"
                                            onClick = {()=>this.setState({tipMsg:false})}
                                    >确定</button>
                                </div>
                            </div>
                        </div>
                        :null
                }

            </div>
        )
    }

}

